from flask import Blueprint,render_template,request,g,redirect,url_for,session
from .forms import PostForm,CommentForm,AnnounceForm
from models import PostModel,AnnounceModel,CommentsModel
from exts import db
from utils.ossUtil import AliyunOSSUploader
from datetime import datetime

#当前已完成大部分功能，本模块类似校园集市
#当前存在问题：
#但是由于jinjia2模版使用导致部分css样式出现问题（哥们轻轻地碎了），样式待修改
#图片的上传存在问题，但是图片的上传不是硬要求，搞明白原因了后续会解决
#点赞功能未做等等偏社交的功能未做
#公告发布需要对当前登录的用户进行权限识别，为学生用户可以发帖，管理员可以发公告
#导航栏对应的分类未做
#目前做了点东西，但是不能掩盖做了一坨的实质，碎了*2
#-------5.11--------


#当前已完成大部分功能，本模块类似校园集市
#当前存在问题：
#图片的上传存在问题，但是图片的上传不是硬要求，搞明白原因了后续会解决
#点赞功能未做等等偏社交的功能未做
#公告发布需要对当前登录的用户进行权限识别，为学生用户可以发帖，管理员可以发公告
#-------5.12--------

#当前已完成大部分功能，本模块类似校园集市
#当前存在问题：
#图片的上传存在问题，但是图片的上传不是硬要求，搞明白原因了后续会解决
#部分css样式待修改
#根据数据量设置分页
#公告发布需要对当前登录的用户进行权限识别，为学生用户可以发帖，管理员可以发公告
#-------5.13--------

community = Blueprint("community", __name__, url_prefix="/community")

@community.route("/test")
def test():
    return "test"

@community.route('/')
def index():
    #首页初始化：对所有帖子，公告进行倒序排列
    posts = PostModel.query.order_by(PostModel.create_time.desc()).all()
    author_id = session.get('admin_id')
    my_posts = PostModel.query.filter(PostModel.author_id == author_id).order_by(PostModel.create_time.desc()).all()
    announces = AnnounceModel.query.order_by(AnnounceModel.create_time.desc()).all()
    return render_template("community/community_main.html",posts = posts,announces = announces,my_posts = my_posts)
    #return render_template("community/community_main.html")



#两个发布，后期需要对用户和管理员进行权限判断，届时方法合并
@community.route('/postpost',methods = ['GET','POST'])
def postpost():
    if request.method == 'POST':
        form = PostForm(request.form)#表单验证无法成功
        if form.validate():
            print("表单成功")
            title = form.title.data
            content = form.content.data
            type = request.form.get('category')
            uploader = AliyunOSSUploader()
            #以当前时间作为唯一图片名，后续修改
            remote_file_name = datetime.now
            localUrl = request.form.get('imageUrl')
            if localUrl:
                image_url = uploader.upload_image(localUrl, remote_file_name)
                author_id = session.get('admin_id')
                post = PostModel(title=title, content=content, image_url=image_url, type=type, author_id=author_id)
                db.session.add(post)
                db.session.commit()
            else:
                author_id = session.get('admin_id')
                post = PostModel(title=title,content=content,image_url='',type = type,author_id=author_id)
                db.session.add(post)
                db.session.commit()
            return redirect(url_for('community.index'))
        else:
            print("表单失败")
            return redirect(url_for('community.postpost'))
    else:
        return render_template('community/community_post.html')


@community.route('/postannounce',methods = ['GET','POST'])
def postannounce():
    if request.method == 'POST':
        form = AnnounceForm(request.form)
        if form.validate():
            title = form.title.data
            content = form.content.data
            uploader = AliyunOSSUploader()
            # 以当前时间作为唯一图片名，后续修改
            remote_file_name = datetime.now
            localUrl = request.form.get('imageUrl')
            if localUrl:
                image_url = uploader.upload_image(localUrl, remote_file_name)
                author_id = session.get('admin_id')
                post = AnnounceModel(title=title, content=content, image_url=image_url, author_id=author_id)
                db.session.add(post)
                db.session.commit()
            else:
                author_id = session.get('admin_id')
                post = PostModel(title=title, content=content, image_url='', author_id=author_id)
                db.session.add(post)
                db.session.commit()
            return redirect(url_for('community.index'))
        else:
            print(form.errors)
            return redirect(url_for('community.postannounce'))
    else:
        return render_template('community/community_main.html')
#发布评论
@community.route('/postcomment',methods = ['POST'])
def postcomment():
    form = CommentForm(request.form)
    if form.validate():
        content = form.content.data
        post_id = form.post_id.data
        author_id = session.get('admin_id')#登录用户的id目前与admin_id绑定
        comment = CommentsModel(post_id=post_id, content=content, author_id=author_id)
        db.session.add(comment)
        db.session.commit()
        return redirect(url_for('community.post_detail', post_id=post_id))
    else:
        print(form.errors)
        return redirect(url_for('community.post_detail', post_id=request.form.get('comment_id')))
#帖子详情
@community.route('/post/detail/<post_id>')
def post_detail(post_id):
    post = PostModel.query.get(post_id)
    comments = CommentsModel.query.all()
    return render_template("community/post_detail.html",post=post,comments = comments)
#公告详情
@community.route('/announce/detail/<announce_id>')
def announce_detail(announce_id):
    announce = AnnounceModel.query.get(announce_id)
    return render_template("community/announce.html",announce=announce)
#帖子搜索
@community.route('/search')
def search():
    #怎么拿到用户的关键字？
    #1.查询字符串 /search?q=flask
    #2.关键字固定在路径 /search/<q>
    #3.post,request.form去拿参数
    key = request.args.get('key')
    posts = PostModel.query.filter(PostModel.title.contains(key)).all()
    title = '搜索结果'
    announces = AnnounceModel.query.order_by(AnnounceModel.create_time.desc()).all()
    return render_template("community/search_post.html",posts=posts,title=title,announces=announces)

@community.route('/category/<post_type>')
def category(post_type):
    find_posts = PostModel.query.filter(PostModel.type == post_type).order_by(PostModel.create_time.desc()).all()
    if(post_type == '1'):
        title = '读者社区'
    elif(post_type == '2'):
        title = '图书专区'
    elif(post_type == '3'):
        title = '资源分享'
    else:
        title = '打听求助'
    announces = AnnounceModel.query.order_by(AnnounceModel.create_time.desc()).all()
    return render_template("community/search_post.html",posts=find_posts,title=title,announces=announces)

